package com.cqupt.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqupt.common.log.annotation.OperationLog;
import com.cqupt.pojo.ResponseMessage;
import com.cqupt.service.ProblemService;
import com.cqupt.utils.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.awt.geom.AreaOp;

import java.util.*;

/**
 * 警告相关请求
 *
 **/
@CrossOrigin
@Controller
@RequestMapping("problem")
@ResponseBody
public class ProblemController {
    private final ProblemService problemService;

    @Autowired
    public ProblemController(ProblemService problemService) {
        this.problemService = problemService;
    }

    /**
     * 获取当前未处理的告警信息
     *
     * @param checkList 选择的严重等级
     * @param hostIds 选择的hostIds
     * @param currentPage 当前页
     * @param pageSize 每页大小
     * @return 封装的返回消息，含result(所有结果)和dataNum(数据总数)
     */
    @RequestMapping("/get_current_unhandled_problem")
    public ResponseMessage getCurrentUnhandledProblem(@RequestParam(value = "check_list", required = false) String checkList,
                                                       @RequestParam(value = "host_ids", required = false) String hostIds,
                                                       @RequestParam(value = "current_page") String currentPage,
                                                       @RequestParam(value = "page_size") String pageSize,
                                                       @RequestParam(value = "objectid", required = false) String objectid
    ) {
        ResponseMessage temp = new ResponseMessage();

        final Map<String, Object> resultMap = problemService.getUnhandledProblems(checkList, hostIds, currentPage, pageSize,objectid);
        ResponseMessage responseMessage = TextUtils.packDataToResponseMessage(temp, resultMap);

        return responseMessage;
    }

    /**
     * 根据主机hostid获取其当前未处理告警信息，并根据严重等级进行分类
     * post-请求
     * @param params hostids(Array)
     * @return
     */
    @RequestMapping("/getCurrentUnhandledProblemByHostids")
    public ResponseMessage getCurrentUnhandledProblemByHostids(@RequestBody Map<String,Object> params){
        // 参数获得
        ArrayList hostids =  (ArrayList) params.get("hostids");

        // 数据请求
        List<Map<String,Object>> alertInformation = null;
        if(hostids != null & hostids.size() != 0){
            alertInformation = problemService.getAlertInformationByHostids(hostids);
        }

        // 封装返回结果
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String,Object> result = new HashMap<>();

        result.put("result",alertInformation);
        responseMessage.setStatus(true);
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * (该接口暂时未被使用)获取当前未处理警告的分类统计
     *
     * @return 封装的返回消息，含result(统计结果)
     */
//    @RequestMapping("/get_current_unhandled_problem_count")
    public ResponseMessage getCurrentUnhandledProblemCount(){
        ResponseMessage temp = new ResponseMessage();

        final String[] resStrArray = problemService.getUnhandledProblemsCount();
        ResponseMessage responseMessage = TextUtils.packCountToResponseMessage(temp, resStrArray);

        return responseMessage;
    }

    /**
     * 获取已处理的告警信息
     *
     * @param checkList 选择的严重等级
     * @param timeOfSeverity 选择的时间范围
     * @param currentPage 当前页
     * @param pageSize 每页大小
     * @return 封装的返回消息，含result(所有结果)和dataNum(数据总数)
     */
    @RequestMapping("/get_history_problem")
    public ResponseMessage getHistoryProblem(@RequestParam(value = "check_list", required = false) String checkList,
                                              @RequestParam(value = "host_ids", required = false) String hostIds,
                                              @RequestParam(value = "time_of_severity", required = false) String timeOfSeverity,
                                              @RequestParam(value = "current_page") String currentPage,
                                              @RequestParam(value = "page_size") String pageSize
    ) {
        ResponseMessage temp = new ResponseMessage();

        final Map<String, Object> resultMap = problemService.getAcknowledgedProblems(checkList, hostIds, timeOfSeverity, currentPage, pageSize);
        ResponseMessage responseMessage = TextUtils.packDataToResponseMessage(temp, resultMap);

        return responseMessage;
    }


    @RequestMapping("/test_proble")
    public ResponseMessage testProblem() {
        ResponseMessage temp = new ResponseMessage();

        List<Map<String, Object>> resultMap = problemService.getProblems_new(true,"未分类,信息类,警告","10654,10681,10682","1341017842399,1656377842399");
        temp.setContent(resultMap.get(0));

        return temp;
    }

    /**
     * 获取已处理告警的分类统计
     *
     * @return 封装的返回消息，含result(统计结果)
     */
    @RequestMapping("/get_history_problem_count")
    public ResponseMessage getHistoryProblemCount(@RequestParam(value = "check_list", required = false) String checkList,
                                                  @RequestParam(value = "host_ids", required = false) String hostIds,
                                                  @RequestParam(value = "time_of_severity", required = false) String timeOfSeverity) {
        ResponseMessage temp = new ResponseMessage();

        final String[] resStrArray = problemService.getAcknowledgedProblemsCount_New(checkList,hostIds,timeOfSeverity);
        ResponseMessage responseMessage = TextUtils.packCountToResponseMessage(temp, resStrArray);

        return responseMessage;
    }

    /**
     * 确认当前未处理告警
     *
     * @param eventId 要关闭的告警eventId
     * @param descriptionDetail 添加的描述
     * @return 封装的返回消息，status表示是否正常
     */
    @OperationLog(level = "信息", object = "未处理告警", operationType = "处理告警")
    @RequestMapping("/acknowledge_current_unhandled_problem")
    public ResponseMessage acknowledgeProblem(@RequestParam(value = "event_id") String eventId,
                                               @RequestParam(value = "description_detail", required = false) String descriptionDetail,
                                                @RequestParam(value = "question_name", required = false) String question_name){
        ResponseMessage responseMessage = new ResponseMessage();

        Map<String, Object> resultMap;
        Map<String, Object> resMap = new HashMap<>();
        //忽略告警，禁用触发器
        if(Objects.equals(descriptionDetail, "此告警项已被忽略")){
            //确认告警

            problemService.ignoreknowledgeProblem(eventId, descriptionDetail);
            resultMap= problemService.acknowledgeProblem(eventId,descriptionDetail);
            responseMessage.setStatus(resultMap.get("status").equals("true"));
            ////可能会关闭失败。如交换机不允许自动关闭
            problemService.closeProblem(eventId);
            if (resultMap.get("status").equals("true")){
                resMap.put("log_objectName",question_name);
                resMap.put("log_description","忽略告警["+question_name+"]");
            }else {
                responseMessage.setErrorCode("已存在"+question_name+"!");
            }

        }else if(Objects.equals(descriptionDetail, "关机") ||Objects.equals(descriptionDetail, "重启")) {
            resultMap = problemService.acknowledgeProblem(eventId, descriptionDetail);
            responseMessage.setStatus(resultMap.get("status").equals("true"));
            if (resultMap.get("status").equals("true")){
                resMap.put("log_objectName",question_name);
                resMap.put("log_description",descriptionDetail);
            }else {
                responseMessage.setErrorCode("已存在"+question_name+"!");
            }
        }else{
            resultMap = problemService.acknowledgeProblem(eventId, descriptionDetail);
            responseMessage.setStatus(resultMap.get("status").equals("true"));
            if (resultMap.get("status").equals("true")){
                resMap.put("log_objectName",question_name);
                resMap.put("log_description","确认告警");
            }else {
                responseMessage.setErrorCode("已存在"+question_name+"!");
            }
        }
        responseMessage.setContent(resMap);
        return responseMessage;
    }

    /**
     * (该接口暂时未被使用)关闭当前未处理告警
     *
     * @param eventId 要关闭的问题eventId
     * @return 封装的返回消息，status表示是否正常
     */
//    @RequestMapping("/close_current_unhandled_problem")
    public ResponseMessage closeCurrentUnhandledProblem(@RequestParam(value = "event_id") String eventId){
        ResponseMessage responseMessage = new ResponseMessage();

        final Map<String, Object> resultMap = problemService.closeProblem(eventId);
        responseMessage.setStatus(resultMap.get("status").equals("true"));

        return responseMessage;
    }

    /*
    * 更具eventid获取告警项的解决方案
    * */
    @RequestMapping("/get_solution")
    public ResponseMessage getSolution(@RequestParam(value = "event_id") String eventId){

        ResponseMessage temp = new ResponseMessage();

        final Map<String, Object> resultMap = problemService.getSolutionByEventId(eventId);
        ResponseMessage responseMessage = TextUtils.packDataToResponseMessage(temp, resultMap);

        return responseMessage;

    }



    /**
     * 根据触发器ID获得事件信息（已过滤）
     * 未分页
     * 英译汉
     * @return
     */
    @RequestMapping("/get_unhandle_events")
    public ResponseMessage getEventByHostID(@RequestParam(value = "check_list", required = false) String checkList,
                                             @RequestParam(value = "host_ids", required = false) String hostIds,
                                             @RequestParam(value = "current_page") String currentPage,
                                             @RequestParam(value = "page_size") String pageSize){

        ResponseMessage responseMessage = new ResponseMessage();
        final Map<String, Object> responseMap = problemService.PagingHostList(checkList,hostIds,currentPage,pageSize);
        responseMessage.setContent(responseMap);
        return responseMessage;
    }

    /**
     * 得到选中的主机列表和安全性的告警信息
     * check_list 选中的严重性列表字符串、host_ids 选中的主机、current_page当前页、page_size 页面大小
     * @return 最近的未处理告警
     */
    @RequestMapping("/get_alter_unhandle_events")
    public ResponseMessage getAlterEventByHostID(@RequestParam(value = "check_list", required = false) String checkList,
                                                  @RequestParam(value = "host_ids", required = false) String hostIds,
                                                  @RequestParam(value = "current_page") String currentPage,
                                                  @RequestParam(value = "page_size") String pageSize){

        ResponseMessage responseMessage = new ResponseMessage();
        // 根据传入 hostIds 和 checkList 调用不同的逻辑
        if (hostIds!="" && checkList==""){
            // 获取所有的主机
            final List<Map<String, Object>> response = problemService.getAllOnlineHostName(hostIds);
            String hostnames = "";
            String hostids = "";
            checkList="未分类,信息类,警告,一般严重,严重,灾难";
            // 遍历获取 主机id 和 主机名
            for(int i=0;i<response.size();i++){
                hostids =hostids+","+response.get(i).get("hostid");
                hostnames =hostnames +","+ response.get(i).get("host");
            }
            final Map<String, Object> responseMap = problemService.PagingAlterHostList(checkList,hostids,hostnames,currentPage,pageSize);
            responseMessage.setContent(responseMap);
            return responseMessage;
        } else if (hostIds=="" && checkList!=""){
            final List<Map<String, Object>> response = problemService.getAllOnlineHostName();
            String hostnames = "";
            String hostids = "";
            for(int i=0;i<response.size();i++){
                hostids =hostids+","+response.get(i).get("hostid");
                hostnames =hostnames +","+ response.get(i).get("host");
            }
            hostids = hostids.substring(1);
            hostnames = hostnames.substring(1);
            final Map<String, Object> responseMap = problemService.PagingAlterHostList(checkList,hostids,hostnames,currentPage,pageSize);
            responseMessage.setContent(responseMap);
            return responseMessage;
        }else {
            final List<Map<String, Object>> response = problemService.getAllOnlineHostName(hostIds);
            String hostnames = "";
            String hostids = "";
            for(int i=0;i<response.size();i++){
                hostids =hostids+","+response.get(i).get("hostid");
                hostnames =hostnames +","+ response.get(i).get("host");
            }
            hostids = hostids.substring(1);
            hostnames = hostnames.substring(1);
            final Map<String, Object> responseMap = problemService.PagingAlterHostList(checkList,hostids,hostnames,currentPage,pageSize);
            responseMessage.setContent(responseMap);
            return responseMessage;
        }
    }

    /**
     * 根据index移除当前页的报警信息
     * @param index 索引值
     * @return 操作是否成功
     */
    @RequestMapping("/delete_a_unhandle_events")
    public ResponseMessage deleteAEventByHostID(@RequestParam(value = "index",required = false) String index){
        ResponseMessage responseMessage = new ResponseMessage();
        final Map<String, Object> responseMap = problemService.deleteARecentProblemEvents(index);
        responseMessage.setContent(responseMap);
        return responseMessage;
    }

    /**默认查询调用接口时间前推604,800秒(七天)
     * 7天内每天的未处理告警数据
     * @return
     */
    @RequestMapping("/get_a_week_unhandled_events")
    public ResponseMessage get_week_unhandled_events() {
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> weekEvents = problemService.getWeekUnhandledEvents();
        responseMessage.setStatus(true);
        responseMessage.setContent(weekEvents);
        return responseMessage;
    }

    /**默认查询调用接口时间前推604,800秒(七天)
     * 7天内每天的已处理告警总数
     * @return
     */
    @RequestMapping("/get_a_week_processed_events")
    public ResponseMessage get_week_processed_events() {
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> weekEvents = problemService.getWeekProcessedEvents();
        responseMessage.setStatus(true);
        responseMessage.setContent(weekEvents);
        return responseMessage;
    }
}
